//
//  OpenLockVC.m
//  AILock
//
//  Created by 谭亚明 on 2020/7/13.
//  Copyright © 2020 tym. All rights reserved.
//

#import "OpenLockVC.h"
#import "LockUsersVC.h"
#import "UIImage+GIF.h"
#import "Sizes.h"
#import "GFWaterView.h"
#import "ShowAlertView.h"
#import "HBLockSliderView.h"
#import "UIImageView+YPImage.h"
#import "UIButton+ImageTitleSpacing.h"
#import "UIView+ZFFrame.h"
#import "EquipmentNameVC.h"
#import "InputPasswordView.h"
#import "EquipmentService.h"
#import "UIimage+Extends.h"
#import "LockManagerVC.h"
#import "MessageHistoryVC.h"

@interface OpenLockVC ()<HBLockSliderDelegate>


@property(nonatomic,weak) IBOutlet UIView *blueView;
@property(nonatomic,weak) IBOutlet UIView *botView;

@property(nonatomic,weak) IBOutlet UIButton *xinhaoBtn;
@property(nonatomic,weak) IBOutlet UIButton *blueBtn;
@property(nonatomic,weak) IBOutlet UIButton *eleBtn;

@property(nonatomic,weak) IBOutlet UILabel *titleLab;
@property(nonatomic,weak) IBOutlet UIImageView *testImage;

@property(nonatomic,strong)  EquipmentService *services;

@property (nonatomic,strong) HBLockSliderView *sliderBtn;

@property(nonatomic,strong) UIImageView *animationImage;

@property(nonatomic,weak) NSTimer *timer;

@property(nonatomic,assign) NSInteger seconds;
@end

@implementation OpenLockVC

-(instancetype)initWithEquipment:(EquipmentModel*)model{
    self = [super init];
    self.equipMent = model;
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.titleLab.text = _equipMent.equipmentName;
    [self initBlueView];
    
    [self addBackBtnFunc];
    
    _sliderBtn = [[HBLockSliderView alloc] initWithFrame:CGRectMake((ScreenWidth - 20)/2 - 185/2, 15, 185, 45)];
    _seconds = 60;
    _sliderBtn.delegate = self;
    [self.botView addSubview:_sliderBtn];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateLockState:) name:@"updateLockState" object:nil];
    
    __weak typeof(self) weakSelf = self;
    if (@available(iOS 10.0, *)) {
        self.timer = [NSTimer scheduledTimerWithTimeInterval:0.5 repeats:YES block:^(NSTimer * _Nonnull timer) {
            [weakSelf clickAnimation];
        }];
    } else {
        NSTimer *timer = [NSTimer timerWithTimeInterval:0.7 target:self selector:@selector(clickAnimation) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
        self.timer = timer;
    }
    
    [self.view addSubview:self.animationImage];
}

-(void)setEquipmentUI{
    [self.eleBtn setTitle:[NSString stringWithFormat:@"%@%%",self.equipMent.electricQuantity?self.equipMent.electricQuantity:@(0)] forState:UIControlStateNormal];
    
    if (self.equipMent.online) {
        [self.eleBtn setImage:[UIImage imageNamed:[self elecBtnImage:self.equipMent.electricQuantity]] forState:UIControlStateNormal];
        [self.xinhaoBtn setImage:[UIImage imageNamed:[self wiftBtnImage:self.equipMent.wifiStrength]] forState:UIControlStateNormal];
        [self.blueBtn setImage:[UIImage imageNamed:@"icon_equipment_nor1"] forState:UIControlStateNormal];
        [self.eleBtn setAlpha:1];
        [self.blueBtn setAlpha:0.5];
        [self.xinhaoBtn setAlpha:1];
    }else{
        [self.xinhaoBtn setImage:[UIImage imageNamed:[self wiftBtnImage:self.equipMent.wifiStrength]] forState:UIControlStateNormal];
        [self.eleBtn setImage:[UIImage imageNamed:[self elecBtnImage:self.equipMent.electricQuantity]] forState:UIControlStateNormal];
        [self.blueBtn setImage:[UIImage imageNamed:@"icon_equipment_nor1"] forState:UIControlStateNormal];
        
        [self.eleBtn setAlpha:0.5];
        [self.blueBtn setAlpha:0.5];
        [self.xinhaoBtn setAlpha:0.5];
    }
    
    [self.eleBtn layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleLeft imageTitleSpace:3 ];
    [self.xinhaoBtn layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleLeft imageTitleSpace:3 ];
}

- (void)clickAnimation{
    
    float waterW = 420;
    __block GFWaterView *waterView = [[GFWaterView alloc]initWithFrame:CGRectMake(ScreenWidth/2 - waterW/2, 120, waterW, waterW)];
    waterView.center = self.testImage.center;
    waterView.backgroundColor = [UIColor clearColor];
    [self.view insertSubview:waterView atIndex:1];
    
    [UIView animateWithDuration:2.5 animations:^{
        waterView.transform = CGAffineTransformScale(waterView.transform, 2, 2);
        waterView.alpha = 0;
    } completion:^(BOOL finished) {
        [waterView removeFromSuperview];
        waterView = nil;
    }];
}

-(NSString*)elecBtnImage:(NSNumber*)elecValue{
    
    if (elecValue == nil || [elecValue intValue] <= 20) {
        return @"icon_equipment903";
    }else if([elecValue integerValue] <= 40 ){
        return @"icon_battery4";
    }else if([elecValue intValue] <= 70){
        return @"icon_battery7";
    }
    return @"icon_battery10";
}

-(NSString*)wiftBtnImageLixian:(NSInteger)wifiValue{
    if (!wifiValue) {
        return @"icon_equipment103";
    }else if(wifiValue < 5){
        return @"icon_equipment102";
    }else if(wifiValue < 20){
        return @"icon_equipment104";
    }else if(wifiValue < 30){
        return @"icon_equipment100";
    }else if(wifiValue < 50){
        return @"icon_equipment101";
    }
    return @"icon_equipment11";
}

-(NSString*)wiftBtnImage:(NSInteger)wifiValue{
    if (!wifiValue) {
        return @"icon_equipment103";
    }else if(wifiValue < 5){
        return @"icon_equipment102";
    }else if(wifiValue < 20){
        return @"icon_lock_equipment7";
    }else if(wifiValue < 30){
        return @"icon_lock_equipment6";
    }else if(wifiValue < 50){
        return @"icon_lock_equipment5";
    }
    return @"icon_lock_equipment2";
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.animationImage.frame = CGRectMake(ScreenWidth/2-5, 236, 52.5, 10.5);
    [self getEquipmentOpenCloseStatus];
    [self.navigationController navigationController:self.navigationController willShowViewController:self animated:YES];
}

-(UIImageView*)animationImage{
    if (_animationImage == nil) {
        _animationImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"lock_big2"]];
    }
    return _animationImage;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}

-(void)rouseEquipMentAction:(UIButton*)sender{
    
    [ShowAlertView showAlertViewTitle:@"提示" message:@"请唤醒设备,并接入网络" actionBtnTitle:@"确定"
                         hiddenCancel:NO
                           completion:^(NSInteger actionType) {
    }];
}

//更新锁的状态
-(void)updateLockState:(NSNotification *) notification{
    
    NSDictionary *dic = notification.object[@"data"];
    if([dic[@"equipmentId"] integerValue] != self.equipMent.equipmentId){
        return;
    }
    
    if ([notification.object[@"code"] integerValue] == 50) {
        //门锁打开
        if ([dic[@"status"] intValue] == 1) {
            [self changeSecend];
            [self.sliderBtn setIsCanOpenLock:YES];
        }else if([dic[@"status"] intValue] == 2){
            [self.sliderBtn setIsCanOpenLock:NO];
        }
    }else if([notification.object[@"code"] integerValue] == 29){
        [self changeSecend];
        [self.sliderBtn setIsCanOpenLock:YES];
    }
}

-(void)changeSecend{
    if (_seconds > 0) {
        _seconds =_seconds-1;
        [self performSelector:@selector(changeSecend) withObject:self afterDelay:1];
    } else{
        [self.sliderBtn setIsCanOpenLock:NO];
        [NSObject cancelPreviousPerformRequestsWithTarget:self];
        _seconds = 60;
    }
}

-(void)initBlueView{
    CAGradientLayer *gl = [CAGradientLayer layer];
    gl.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight- 216-SafeBottomMargin);
    gl.startPoint = CGPointMake(0, 0.5);
    gl.endPoint = CGPointMake(1, 0.5);
    gl.colors = @[(__bridge id)[UIColor colorWithRed:76/255.0 green:132/255.0 blue:255/255.0 alpha:1.0].CGColor, (__bridge id)[UIColor colorWithRed:139/255.0 green:175/255.0 blue:255/255.0 alpha:1.0].CGColor];
    gl.locations = @[@(0), @(1.0f)];
    [self.blueView.layer addSublayer:gl];
    
    self.botView.zf_width = ScreenWidth - 20;
    [self.botView showTopCircularDead];
}

-(void)updateData{
    
    self.titleLab.text= self.equipMent.name;
    if (_equipMent.openCloseStatus == 1) {
        [self.sliderBtn setIsCanOpenLock:NO];
    }else{
        [self.sliderBtn setIsCanOpenLock:YES];
    }
    [self setEquipmentUI];
}

-(EquipmentService*)services{
    if(_services == nil){
        _services = [[EquipmentService alloc] init];
    }
    return _services;
}

-(void)openEquipmentWithPassword:(NSString *)password{
    TYMWeak(self);
    [self.services getOpenclosedoorapplyequipmentId:_equipMent.equipmentId commandType:1 operationPassword:password completion:^(LMJBaseResponse * _Nonnull respons) {
        if (respons.message) {
            [WHToast showMessage:respons.message duration:2 finishHandler:nil];
        }else{
            [weakself animationView:self.animationImage];
            //[weakself openLockAnimation];
            [WHToast showMessage:@"开锁成功" duration:2 finishHandler:nil];
            [weakself.sliderBtn setIsCanOpenLock:NO];
        }
        
    }];
}

- (void)sliderEndValueChanged:(HBLockSliderView *)slider{
    
    if (slider.isCanOpen) {
        [InputPasswordView showInputPasswordViewcompletion:^(NSString * _Nonnull passwordStr) {
            if (passwordStr.length==6) {
                [self openEquipmentWithPassword:passwordStr];
            }
        }];
    }else{  //锁还没有连接
        [ShowAlertView showAlertViewTitle:@"提示" message:@"请先在锁端按下门铃!" actionBtnTitle:@"确定"
                             hiddenCancel:NO
                               completion:^(NSInteger actionType) {
        }];
    }
}

-(void)animationView:(UIView*)view{
    
    CGPoint oldOrigin = view.frame.origin;
    view.layer.anchorPoint = CGPointMake(0, 0.5);
    CGPoint newOrigin = view.frame.origin;
    CGPoint transition;
    transition.x = newOrigin.x - oldOrigin.x;
    transition.y = newOrigin.y - oldOrigin.y;
    view.center = CGPointMake (ScreenWidth/2-5, view.center.y - transition.y);
    [UIView animateWithDuration:4 animations:^{
        [UIView animateWithDuration:2 animations:^{
            view.transform = CGAffineTransformMakeRotation(M_PI_4 * -1);
        }];
    } completion:^(BOOL finished) {
        if (finished) {
            [UIView animateWithDuration:2 animations:^{
                view.transform = CGAffineTransformMakeRotation(M_PI_4*0);
            }];
        }
    }];
}

-(IBAction)backAction:(id)sender{
    if (self.navigationController.viewControllers.count>1) {
        [super backViewFunc:nil];
    }else{
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

-(IBAction)editAction:(id)sender{
    EquipmentNameVC *equipVC = [[EquipmentNameVC alloc] init];
    equipVC.equipMentID = self.equipMent.equipmentId;
    equipVC.nameStr = self.equipMent.name;
    [self.navigationController pushViewController:equipVC animated:YES];
}

//更多设置
-(IBAction)moreSettingAction:(id)sender{
    LockManagerVC *managerVC = [[LockManagerVC alloc] initWithEquipment:self.equipMent];
    [self.navigationController pushViewController:managerVC animated:YES];
}

//开锁记录
-(IBAction)openLockHistoryAction:(id)sender{
    MessageHistoryVC *historyVC = [[MessageHistoryVC alloc] initWithModel:self.equipMent];
    [self.navigationController pushViewController:historyVC animated:YES];
}

//门锁用户
-(IBAction)lockUsersAction:(id)sender{
    
    LockUsersVC *lockUsers = [[LockUsersVC alloc] initWithEquipment:self.equipMent];
    [self.navigationController pushViewController:lockUsers animated:YES];
}

-(void)getEquipmentOpenCloseStatus{
    TYMWeak(self);
    [self.services getEquipmentequipmentId:self.equipMent.equipmentId  completion:^(LMJBaseResponse * _Nonnull resp, EquipmentModel * _Nonnull equipment) {
        if (resp.message) {
            [WHToast showMessage:resp.message duration:2 finishHandler:nil];
        }else{
            weakself.equipMent = equipment;
            [weakself updateData];
        }
    }];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"updateLockState" object:nil];
    [_timer invalidate];
    _timer = nil;
}


@end
